# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-14
# File     : dependencies.py
# Project  : codebuddy_craft
# Desc     : 依赖项

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Optional

from backend.database.connection import get_db
from backend.models.user import User
from backend.utils.security import decode_access_token

# OAuth2 密码流认证
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")

async def get_user_from_token(token: str, db: AsyncSession) -> Optional[User]:
    """
    从令牌获取用户
    
    验证JWT令牌并返回用户，适用于WebSocket连接
    """
    # 解码令牌
    user_id = decode_access_token(token)
    if not user_id:
        return None
    
    # 查询用户
    from sqlalchemy import select
    result = await db.execute(select(User).where(User.id == user_id))
    user = result.scalar_one_or_none()
    
    return user

async def get_current_user(
    token: str = Depends(oauth2_scheme),
    db: AsyncSession = Depends(get_db)
) -> User:
    """
    获取当前用户
    
    验证JWT令牌并返回当前用户
    """
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="无效的身份验证凭据",
        headers={"WWW-Authenticate": "Bearer"},
    )
    
    # 解码令牌
    user_id = decode_access_token(token)
    if not user_id:
        raise credentials_exception
    
    # 查询用户
    from sqlalchemy import select
    result = await db.execute(select(User).where(User.id == user_id))
    user = result.scalar_one_or_none()
    
    if user is None:
        raise credentials_exception
    
    if not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="用户已被禁用"
        )
    
    return user

async def get_current_active_user(
    current_user: User = Depends(get_current_user)
) -> User:
    """
    获取当前活跃用户
    
    确保用户处于活跃状态
    """
    if not current_user.is_active:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="用户已被禁用"
        )
    return current_user

async def get_current_admin_user(
    current_user: User = Depends(get_current_user)
) -> User:
    """
    获取当前管理员用户
    
    确保用户具有管理员权限
    """
    if not current_user.is_superuser:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="需要管理员权限"
        )
    return current_user